package com.zhiqian.community.controller;

import com.google.code.kaptcha.Producer;
import com.zhiqian.community.entity.User;
import com.zhiqian.community.service.LoginService;
import com.zhiqian.community.service.UserService;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.CommunityUtil;
import com.zhiqian.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger= LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer producer;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @GetMapping("/register")
    public String getRegisterPage(){
        return "/site/register";
    }

    @RequestMapping("/loginPage")
    public String getLoginPage(){
        return "/site/login";
    }

    @GetMapping("/denied")
    public String getDeniedPage(){
        return "/error/404";
    }

    @PostMapping("/register")
    public String register(Model model, User user){
        Map<String, Object> map = userService.register(user);
        if (map.isEmpty()){
            model.addAttribute("msg","注册成功，我们已向您的邮箱发送了激活邮件，请激活");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }
        model.addAttribute("usernameMsg",map.get("usernameMsg"));
        model.addAttribute("passwordMsg",map.get("passwordMsg"));
        model.addAttribute("emailMsg",map.get("emailMsg"));
        return "/site/register";
    }
    @GetMapping("/activation/{userId}/{activationCode}")
    public String activation(Model model, @PathVariable("userId")int userId,@PathVariable("activationCode")String activationCode){
        int state = userService.activation(userId, activationCode);
        if (state==ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功,您的账号可以正常使用了!");
            model.addAttribute("target","/login");
        }else if (state==ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作,请不要重复激活!");
            model.addAttribute("target","/index");
        }else {
            model.addAttribute("msg","激活失败，请输入正确的激活码！");
            model.addAttribute("target","/index");
        }

        return "/site/operate-result";
    }

    //生成验证码
    @GetMapping("/kaptcha")
    public void getKaptcha(@CookieValue(value = "owner",required = false)String owner, HttpServletResponse response){
        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //生成验证码cookie
        if(owner==null) {
            owner = CommunityUtil.generateUUID();
            Cookie cookie = new Cookie("owner", owner);
            cookie.setMaxAge(-1);//设置cookie的生命周期. -1:浏览器不关闭，该cookie默认一直存在
            cookie.setPath(contextPath);//设置cookie的作用范围路径
            response.addCookie(cookie);
        }
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(owner);
        //将验证码存入redis
        redisTemplate.opsForValue().set(kaptchaKey,text,60*3, TimeUnit.SECONDS);
        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            logger.error("响应验证码失败："+e.getMessage());
        }
    }

//    @PostMapping("/login")
//    public String login(@CookieValue(value = "owner",required = false)String owner, Model model,User user,String code,boolean rememberMe,HttpServletResponse response){
//        String kaptchaKey = RedisKeyUtil.getKaptchaKey(owner);
//        String kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
//        if (StringUtils.isBlank(kaptcha)||!kaptcha.equals(code)){
//            model.addAttribute("codeMsg","验证码错误");
//            return "/site/login";
//        }
//        int expiredSeconds=rememberMe?REMEMBER_ME_EXPIRED_SECONDS:DEFAULT_EXPIRED_SECONDS;
//        Map<String, Object> map = loginService.login(user, expiredSeconds);
//        if (!map.containsKey("ticket")){
//            model.addAttribute("usernameMsg",map.get("usernameMsg"));
//            model.addAttribute("passwordMsg",map.get("passwordMsg"));
//            model.addAttribute("errMsg",map.get("errMsg"));
//            return "/site/login";
//        }
//        Cookie cookie = new Cookie("ticket", (String)map.get("ticket"));
//        cookie.setPath(contextPath);
//        cookie.setMaxAge(expiredSeconds);
//        response.addCookie(cookie);
//        return "redirect:/index";
//    }

//    @GetMapping("/logout")
//    public String logout(@CookieValue("ticket") String ticket){
//        loginService.logout(ticket);
//        return "redirect:/index";
//    }

    @GetMapping("/forget")
    public String getForgetPage(){
        return "/site/forget";
    }

    /**
     * 忘记密码：发送验证码
     * @param model
     * @param email
     * @param session
     * @return
     */
    @GetMapping("/sendAuthCode")
    public String sendAuthCode(Model model,String email,HttpSession session){
        Map<String, Object> map = loginService.sendAuthCode(email);
        if(map.containsKey("authCode")){
            session.setAttribute("authCode",map.get("authCode").toString());
            session.setAttribute("timeout",System.currentTimeMillis());
            model.addAttribute("success","验证码已成功发送");
        }
        model.addAttribute("errMsg",map.get("errMsg"));
        return "/site/forget::refresh";
    }


    /**
     * 忘记密码：重置密码
     * @param model
     * @param email
     * @param password
     * @param authCode
     * @param session
     * @return
     */
    @PostMapping("/forget")
    public String forget(Model model,String email,String password,String authCode,HttpSession session){
        String code = (String) session.getAttribute("authCode");
        long time = (long) session.getAttribute("timeout");
        if (StringUtils.isBlank(code)||!code.equals(authCode)){
            model.addAttribute("authCodeMsg","验证码错误");
            return "/site/forget";
        }
        if (System.currentTimeMillis()-time>FORGET_AUTH_CODE){
            model.addAttribute("authCodeMsg","验证码已失效");
            return "/site/forget";
        }
        Map<String, Object> map = userService.updatePassword(email, password);
        if (map.containsKey("success")){
            return "redirect:/login";
        }
        model.addAttribute("errMsg",map.get("errMsg"));
        model.addAttribute("passwordMsg",map.get("passwordMsg"));
        return "/site/forget";
    }
}
